import tushare as ts
from monitor import load_prev_data
from stock import candlestick_charts

def check(ts_code,df):
    specific_stock_data = df[df['ts_code'] == ts_code]
    # 筛选出最近五个交易日的数据
    recent_trading_days = specific_stock_data.nlargest(5, 'trade_date')
    # 计算五个交易日内的最高值和最低值
    high = recent_trading_days['high'].max()
    low = recent_trading_days['low'].min()
    # 计算最高值和最低值的涨跌幅
    pct_change = (high - low) / low
    if pct_change < 0.20:
        # 获取最后一天的数据
        last_day_data = specific_stock_data.iloc[-1]
        if (is_hammer(last_day_data) or is_doji(last_day_data)) and last_day_data['pct_chg'] < 0 :
            return True
        elif(last_day_data['pct_chg'] <5 and (is_long_upper_shadow(last_day_data) or is_medium_dark_candle(last_day_data))):
            return True
    return False


#  下降趋势10% 大阴线 成交了<1.2
def check_big_trend(ts_code,code_volume,df):
    specific_stock_data = df[df['ts_code'] == ts_code]
    # 按 'date' 列进行倒序排序
    _df_code = specific_stock_data.sort_values(by='trade_date', ascending = True)
    # 筛选出最近五个交易日的数据
    recent_trading_days = _df_code.tail(5)
    if recent_trading_days.shape[0] < 5:
        return ''
    # 计算五个交易日内的最高值和最低值
    _min_low = recent_trading_days['low'].min()
    _fist_close = recent_trading_days.iloc[0]['close']
    _yesterday_close = recent_trading_days.iloc[-1]['close']
    _yesterday_volume = recent_trading_days.iloc[-1]['vol']
    _rs = ''
    _fall = ((_fist_close - _yesterday_close) / _fist_close) * 100
    if _fall >= 5:
        if _fall >=10:
            _rs += '5日下降10%,'
        else:
            _rs += '5日下降5-10%,'
        if candlestick_charts.is_long_black_candle(recent_trading_days.iloc[-1]):
            _rs += '昨日大阴线；'
        if code_volume / _yesterday_volume < 1.2:
            _rs += f'当前成交量为昨天的{code_volume / _yesterday_volume:.2f}倍;'
    return _rs

# 定义K线形态的函数
def is_doji(row):
    # 十字星：开盘价和收盘价接近，实体非常小
    body = abs(row['open'] - row['close'])
    total_range = row['high'] - row['low']
    return body / total_range < 0.01 and body < total_range / 2


def is_long_upper_shadow(row):
    # 长上影线：上影线长度至少是实体的两倍
    return (row['high'] - row['close']) > (row['open'] - row['close']) * 2


def is_medium_dark_candle(row):
    # 中阴线：收盘价低于开盘价，且实体大小在一定范围内
    body = abs(row['open'] - row['close'])
    total_range = row['high'] - row['low']
    # 这里需要一个阈值来定义中阴线，例如0.03
    return body / total_range > 0.03 and body / total_range < 0.1

def is_hammer(row):
    # 锤子线：实体位于上端，下影线至少是实体的两倍
    return (row['close'] - row['low']) > (row['high'] - row['close']) * 2


if __name__ =='__main__':
    from datetime import datetime

    old =load_prev_data.load_data(datetime.fromisoformat('2024-03-08'))
    #东财数据
    df = ts.realtime_list(src='dc')
    for index, row in df.iterrows():
        if not row['TS_CODE'].endswith(".BJ") and row['PCT_CHANGE'] > 6.5 and row['PCT_CHANGE'] < 20.5:
            if check(row['TS_CODE'],old):
                print(row['TS_CODE'] ,' ok!')
